package com.bing.util;

import com.bing.beans.Person;
import com.bing.sina.SinaJdbc;
import com.bing.sina.TaoListener;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by kaibb on 14-8-19.
 */
public class FenSiOrGuanZhuParse implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(FenSiOrGuanZhuParse.class);
    private String html;

    private Person person;

    private SinaJdbc sinaJdbc;

    private TaoListener taoListener;

    private int fenSiOrGuanZhu;

    private ExcelUtil excelUtil;

    public FenSiOrGuanZhuParse(String html, Person person, int fenSiOrGuanZhu, SinaJdbc sinaJdbc, TaoListener taoListener, ExcelUtil excelUtil) {
        this.html = html;
        this.person = person;
        this.sinaJdbc = sinaJdbc;
        this.taoListener = taoListener;
        this.fenSiOrGuanZhu = fenSiOrGuanZhu;
        this.excelUtil = excelUtil;
    }


    @Override
    public void run() {
        Document doc = Jsoup.parse(html);
        Elements persons = doc.select("div.PRF_W_wrapl ul.cnfList li div.con_left");
        logger.info("fensi shu:{}", persons.size());
        for (Element e_person : persons) {
            Element name = e_person.select("div.name a").first();
            String p_url = name.attr("usercard").replace("id=", "");
            Person p = sinaJdbc.findPerson(p_url);
            if (p == null) {
                logger.info("新用户......");
                p = new Person();
                p.setUserName(name.text());
                p.setUrl(p_url);
                String connect = e_person.select("div.connect").text();
                TaoMath.setPersonAttr(p, connect);
                Elements renZheng = e_person.select("div.name a i.W_ico16");
                if (renZheng.size() >= 1) {
                    p.setRenZheng(renZheng.first().attr("title"));
                }
                sinaJdbc.savePerson(p);
            } else {
                logger.info("用户已存在:{}", p_url);
            }
            synchronized (person) {
                if (fenSiOrGuanZhu == 1) {
                    sinaJdbc.saveFenSi(person, p);
                    excelUtil.writeFenSi(p);
                    Statistics.fenSi.incrementAndGet();
                } else {
                    sinaJdbc.saveGuanZhu(person, p);
                    excelUtil.writeGuanZhu(p);
                    Statistics.guanZhu.incrementAndGet();
                }
            }
            Statistics.tongji(taoListener);
        }
    }
}
